from django.db import connection,transaction
from django.http import HttpResponse
from django.utils import simplejson as json
from mvc.models import *
import mvc.langs as langs
import traceback
import resources

@transaction.commit_manually
def extract(request):
    try:
        cursor = connection.cursor()
        
        extract_item(cursor)
        extract_skill(cursor)
        extract_task(cursor)
        extract_card(cursor)
        extract_map(cursor)
        extract_campaign(cursor)
        extract_battle_point(cursor)
        extract_level_prop(cursor)
        extract_npc(cursor)
        extract_npc_unit(cursor)
        extract_shop_item(cursor)
        extract_tavern(cursor)        
        extract_versus_battle_point(cursor)
        extract_constants(cursor)
        extract_forge_item_data(cursor)
        extract_item_fragment(cursor)
        extract_item_extra_prop(cursor)
        extract_item_perfect_prop_data(cursor)
        extract_home(cursor)
        extract_open_bag(cursor)        
        extract_silver_bag(cursor)
        extract_gift_bag(cursor)
        extract_treasure(cursor)                
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')



def extractItemAction(request):
    try:
        cursor = connection.cursor()
        extract_item(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_item(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Item,))
    srcdata = cursor.fetchall()
    itemlist = trans_item(cursor,srcdata)
    clear_item()
    for item in itemlist :
        save_item(cursor,item)

def trans_item(cursor,srcdata):
    itemlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'item',rawdata
        srcdict =  json.loads(rawdata)
        item = Item()
        item.deployId = srcdict.get('id', 0)
        item.name = getLanguage(cursor,item.deployId,'name')
        
        item.desc = getLanguage(cursor,item.deployId,'desc')
        
        item.categoryId=srcdict.get('categoryId',-1)
        
        item.typeId=srcdict.get('typeId',-1)
        
        item.attackType=srcdict.get('attackType',-1)
        
        item.level=srcdict.get('level',-1)
        
        item.qualityId=srcdict.get('qualityId',-1)
        
        item.enchantTime=srcdict.get('enchantTime',-1)
        
        item.bindType=srcdict.get('bindType',-1)
        
        item.props=str(srcdict.get('props',[])).replace("u'","'")
        
        item.propertySet=str(srcdict.get('propertySet',{})).replace("u'","'")
        
        item.requiredLevel=srcdict.get('requiredLevel',-1)
        
        item.requiredCareerId=srcdict.get('requiredCareerId',-1)
        
        item.requiredGenderId=srcdict.get('requiredGenderId',-1)
        
        item.unique=srcdict.get('unique',-1)
        
        item.maxStack=srcdict.get('maxStack',-1)
        
        item.recyclingPrice=srcdict.get('recyclingPrice',-1)
        
        item.canSell=srcdict.get('canSell',-1)
        
        item.skillId=srcdict.get('skillId',-1)
        
        item.itemres = resources.getResource(cursor,item.deployId)
        
        itemlist.append(item)
    return itemlist

def clear_item():
    for item in Item.objects.all():
        item.delete()

def save_item(cursor,item):
    namelang = langs.setlang(ModelTypes.Type_Item,item.deployId, 'name', item.name)
    item.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Item,item.deployId, 'desc', item.desc)
    item.desc = desclang.id
        
    item.save()



def extractSkillAction(request):
    try:
        cursor = connection.cursor()
        extract_skill(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_skill(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Skill,))
    srcdata = cursor.fetchall()
    skilllist = trans_skill(cursor,srcdata)
    clear_skill()
    for skill in skilllist :
        save_skill(cursor,skill)

def trans_skill(cursor,srcdata):
    skilllist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'skill',rawdata
        srcdict =  json.loads(rawdata)
        skill = Skill()
        skill.deployId = srcdict.get('id', 0)
        skill.name = getLanguage(cursor,skill.deployId,'name')
        
        skill.desc = getLanguage(cursor,skill.deployId,'desc')
        
        skill.category=srcdict.get('category',-1)
        
        skill.targetType=srcdict.get('targetType',-1)
        
        skill.damage=str(srcdict.get('damage',{})).replace("u'","'")
        
        skill.triggerDamage=str(srcdict.get('triggerDamage',{})).replace("u'","'")
        
        skill.status=str(srcdict.get('status',{})).replace("u'","'")
        
        skill.triggerStatus=str(srcdict.get('triggerStatus',{})).replace("u'","'")
        
        skill.trigger=str(srcdict.get('trigger',{})).replace("u'","'")
        
        skill.property=str(srcdict.get('property',[])).replace("u'","'")
        
        skill.changeFury=srcdict.get('changeFury',-1)
        
        skill.sound=str(srcdict.get('sound',"")).replace("u'","'") 
        
        skill.skillres = resources.getResource(cursor,skill.deployId)
        
        skilllist.append(skill)
    return skilllist

def clear_skill():
    for skill in Skill.objects.all():
        skill.delete()

def save_skill(cursor,skill):
    namelang = langs.setlang(ModelTypes.Type_Skill,skill.deployId, 'name', skill.name)
    skill.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Skill,skill.deployId, 'desc', skill.desc)
    skill.desc = desclang.id
        
    skill.save()



def extractTaskAction(request):
    try:
        cursor = connection.cursor()
        extract_task(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_task(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Task,))
    srcdata = cursor.fetchall()
    tasklist = trans_task(cursor,srcdata)
    clear_task()
    for task in tasklist :
        save_task(cursor,task)

def trans_task(cursor,srcdata):
    tasklist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'task',rawdata
        srcdict =  json.loads(rawdata)
        task = Task()
        task.deployId = srcdict.get('id', 0)
        task.name = getLanguage(cursor,task.deployId,'name')
        
        task.desc = getLanguage(cursor,task.deployId,'desc')
        
        task.level=srcdict.get('level',-1)
        
        task.catalog=srcdict.get('catalog',-1)
        
        task.type=srcdict.get('type',-1)
        
        task.dests=str(srcdict.get('dests',[])).replace("u'","'")
        
        task.compaignId=srcdict.get('compaignId',-1)
        
        task.postTaskId=srcdict.get('postTaskId',-1)
        
        task.startTalk=str(srcdict.get('startTalk',[])).replace("u'","'")
        
        task.endTalk=str(srcdict.get('endTalk',[])).replace("u'","'")
        
        task.deduct=str(srcdict.get('deduct',{})).replace("u'","'")
        
        task.reward=str(srcdict.get('reward',{})).replace("u'","'")
        
        tasklist.append(task)
    return tasklist

def clear_task():
    for task in Task.objects.all():
        task.delete()

def save_task(cursor,task):
    namelang = langs.setlang(ModelTypes.Type_Task,task.deployId, 'name', task.name)
    task.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Task,task.deployId, 'desc', task.desc)
    task.desc = desclang.id
        
    task.save()



def extractCardAction(request):
    try:
        cursor = connection.cursor()
        extract_card(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_card(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Card,))
    srcdata = cursor.fetchall()
    cardlist = trans_card(cursor,srcdata)
    clear_card()
    for card in cardlist :
        save_card(cursor,card)

def trans_card(cursor,srcdata):
    cardlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'card',rawdata
        srcdict =  json.loads(rawdata)
        card = Card()
        card.deployId = srcdict.get('id', 0)
        card.name = getLanguage(cursor,card.deployId,'name')
        
        card.desc = getLanguage(cursor,card.deployId,'desc')
        
        card.module=srcdict.get('module',-1)
        
        card.catalog=srcdict.get('catalog',-1)
        
        card.type=srcdict.get('type',-1)
        
        card.quality=srcdict.get('quality',-1)
        
        card.award=str(srcdict.get('award',{})).replace("u'","'")
        
        card.condition=str(srcdict.get('condition',{})).replace("u'","'")
        
        card.nextCardId=srcdict.get('nextCardId',-1)
        
        card.cardres = resources.getResource(cursor,card.deployId)
        
        cardlist.append(card)
    return cardlist

def clear_card():
    for card in Card.objects.all():
        card.delete()

def save_card(cursor,card):
    namelang = langs.setlang(ModelTypes.Type_Card,card.deployId, 'name', card.name)
    card.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Card,card.deployId, 'desc', card.desc)
    card.desc = desclang.id
        
    card.save()



def extractMapAction(request):
    try:
        cursor = connection.cursor()
        extract_map(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_map(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Map,))
    srcdata = cursor.fetchall()
    maplist = trans_map(cursor,srcdata)
    clear_map()
    for map in maplist :
        save_map(cursor,map)

def trans_map(cursor,srcdata):
    maplist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'map',rawdata
        srcdict =  json.loads(rawdata)
        map = Map()
        map.deployId = srcdict.get('id', 0)
        map.name = getLanguage(cursor,map.deployId,'name')
        
        map.campaignIds=str(srcdict.get('campaignIds',[])).replace("u'","'")
        
        map.mapres = resources.getResource(cursor,map.deployId)
        
        maplist.append(map)
    return maplist

def clear_map():
    for map in Map.objects.all():
        map.delete()

def save_map(cursor,map):
    namelang = langs.setlang(ModelTypes.Type_Map,map.deployId, 'name', map.name)
    map.name = namelang.id
        
    map.save()



def extractCampaignAction(request):
    try:
        cursor = connection.cursor()
        extract_campaign(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_campaign(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Campaign,))
    srcdata = cursor.fetchall()
    campaignlist = trans_campaign(cursor,srcdata)
    clear_campaign()
    for campaign in campaignlist :
        save_campaign(cursor,campaign)

def trans_campaign(cursor,srcdata):
    campaignlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'campaign',rawdata
        srcdict =  json.loads(rawdata)
        campaign = Campaign()
        campaign.deployId = srcdict.get('id', 0)
        campaign.name = getLanguage(cursor,campaign.deployId,'name')
        
        campaign.desc = getLanguage(cursor,campaign.deployId,'desc')
        
        campaign.battlePointIds=str(srcdict.get('battlePointIds',[])).replace("u'","'")
        
        campaign.status=srcdict.get('status',-1)
        
        campaign.vip=srcdict.get('vip',-1)
        
        campaign.mapId=srcdict.get('mapId',-1)
        
        campaign.userLevel=srcdict.get('userLevel',-1)
        
        campaign.coorX=srcdict.get('coorX',-1)
        
        campaign.coorY=srcdict.get('coorY',-1)
        
        campaign.music = resources.getResource(cursor,campaign.deployId)
        
        campaign.frontCompaignIds=str(srcdict.get('frontCompaignIds',[])).replace("u'","'")
        
        campaign.afterCompaignIds=str(srcdict.get('afterCompaignIds',[])).replace("u'","'")
        
        campaignlist.append(campaign)
    return campaignlist

def clear_campaign():
    for campaign in Campaign.objects.all():
        campaign.delete()

def save_campaign(cursor,campaign):
    namelang = langs.setlang(ModelTypes.Type_Campaign,campaign.deployId, 'name', campaign.name)
    campaign.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Campaign,campaign.deployId, 'desc', campaign.desc)
    campaign.desc = desclang.id
        
    campaign.save()



def extractBattle_pointAction(request):
    try:
        cursor = connection.cursor()
        extract_battle_point(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_battle_point(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Battle_point,))
    srcdata = cursor.fetchall()
    battle_pointlist = trans_battle_point(cursor,srcdata)
    clear_battle_point()
    for battle_point in battle_pointlist :
        save_battle_point(cursor,battle_point)

def trans_battle_point(cursor,srcdata):
    battle_pointlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'battle_point',rawdata
        srcdict =  json.loads(rawdata)
        battle_point = Battle_point()
        battle_point.deployId = srcdict.get('id', 0)
        battle_point.name = getLanguage(cursor,battle_point.deployId,'name')
        
        battle_point.desc = getLanguage(cursor,battle_point.deployId,'desc')
        
        battle_point.npcId=srcdict.get('npcId',-1)
        
        battle_point.campaignId=srcdict.get('campaignId',-1)
        
        battle_point.weatherIds=str(srcdict.get('weatherIds',[])).replace("u'","'")
        
        battle_point.roundMax=srcdict.get('roundMax',-1)
        
        battle_point.leaderDead=srcdict.get('leaderDead',-1)
        
        battle_point.roundLimit=srcdict.get('roundLimit',-1)
        
        battle_point.leader=str(srcdict.get('leader',{})).replace("u'","'")
        
        battle_point.round=str(srcdict.get('round',{})).replace("u'","'")
        
        battle_point.endCondition=str(srcdict.get('endCondition',[])).replace("u'","'")
        
        battle_point.attackerMax=srcdict.get('attackerMax',-1)
        
        battle_point.defenderMax=srcdict.get('defenderMax',-1)
        
        battle_point.areaId=srcdict.get('areaId',-1)
        
        battle_point.drops=str(srcdict.get('drops',[])).replace("u'","'")
        
        battle_point.energyCost=srcdict.get('energyCost',-1)
        
        battle_point.passCount=srcdict.get('passCount',-1)
        
        battle_point.difficulty=srcdict.get('difficulty',-1)
        
        battle_point.starMax=srcdict.get('starMax',-1)
        
        battle_point.frontBattlePointIds=str(srcdict.get('frontBattlePointIds',[])).replace("u'","'")
        
        battle_point.afterBattlePointIds=str(srcdict.get('afterBattlePointIds',[])).replace("u'","'")
        
        battle_pointlist.append(battle_point)
    return battle_pointlist

def clear_battle_point():
    for battle_point in Battle_point.objects.all():
        battle_point.delete()

def save_battle_point(cursor,battle_point):
    namelang = langs.setlang(ModelTypes.Type_Battle_point,battle_point.deployId, 'name', battle_point.name)
    battle_point.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Battle_point,battle_point.deployId, 'desc', battle_point.desc)
    battle_point.desc = desclang.id
        
    battle_point.save()



def extractLevel_propAction(request):
    try:
        cursor = connection.cursor()
        extract_level_prop(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_level_prop(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Level_prop,))
    srcdata = cursor.fetchall()
    level_proplist = trans_level_prop(cursor,srcdata)
    clear_level_prop()
    for level_prop in level_proplist :
        save_level_prop(cursor,level_prop)

def trans_level_prop(cursor,srcdata):
    level_proplist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'level_prop',rawdata
        srcdict =  json.loads(rawdata)
        level_prop = Level_prop()
        level_prop.deployId = srcdict.get('id', 0)
        level_prop.exp=srcdict.get('exp',-1)
        
        level_prop.energyMax=srcdict.get('energyMax',-1)
        
        level_prop.battleCount=srcdict.get('battleCount',-1)
        
        level_prop.employeeCount=srcdict.get('employeeCount',-1)
        
        level_prop.skillCount=srcdict.get('skillCount',-1)
        
        level_prop.hp=srcdict.get('hp',-1)
        
        level_prop.physicalatk=srcdict.get('physicalatk',-1)
        
        level_prop.physicaldef=srcdict.get('physicaldef',-1)
        
        level_prop.magicatk=srcdict.get('magicatk',-1)
        
        level_prop.magicdef=srcdict.get('magicdef',-1)
        
        level_prop.award=str(srcdict.get('award',{})).replace("u'","'")
        
        level_prop.logos=str(srcdict.get('logos',[])).replace("u'","'")
        
        level_proplist.append(level_prop)
    return level_proplist

def clear_level_prop():
    for level_prop in Level_prop.objects.all():
        level_prop.delete()

def save_level_prop(cursor,level_prop):
        
    level_prop.save()



def extractNpcAction(request):
    try:
        cursor = connection.cursor()
        extract_npc(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_npc(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Npc,))
    srcdata = cursor.fetchall()
    npclist = trans_npc(cursor,srcdata)
    clear_npc()
    for npc in npclist :
        save_npc(cursor,npc)

def trans_npc(cursor,srcdata):
    npclist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'npc',rawdata
        srcdict =  json.loads(rawdata)
        npc = Npc()
        npc.deployId = srcdict.get('id', 0)
        npc.name = getLanguage(cursor,npc.deployId,'name')
        
        npc.desc = getLanguage(cursor,npc.deployId,'desc')
        
        npc.npcUnitIds=str(srcdict.get('npcUnitIds',[])).replace("u'","'")
        
        npc.npcres = resources.getResource(cursor,npc.deployId)
        
        npclist.append(npc)
    return npclist

def clear_npc():
    for npc in Npc.objects.all():
        npc.delete()

def save_npc(cursor,npc):
    namelang = langs.setlang(ModelTypes.Type_Npc,npc.deployId, 'name', npc.name)
    npc.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Npc,npc.deployId, 'desc', npc.desc)
    npc.desc = desclang.id
        
    npc.save()



def extractNpc_unitAction(request):
    try:
        cursor = connection.cursor()
        extract_npc_unit(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_npc_unit(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Npc_unit,))
    srcdata = cursor.fetchall()
    npc_unitlist = trans_npc_unit(cursor,srcdata)
    clear_npc_unit()
    for npc_unit in npc_unitlist :
        save_npc_unit(cursor,npc_unit)

def trans_npc_unit(cursor,srcdata):
    npc_unitlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'npc_unit',rawdata
        srcdict =  json.loads(rawdata)
        npc_unit = Npc_unit()
        npc_unit.deployId = srcdict.get('id', 0)
        npc_unit.name = getLanguage(cursor,npc_unit.deployId,'name')
        
        npc_unit.desc = getLanguage(cursor,npc_unit.deployId,'desc')
        
        npc_unit.level=srcdict.get('level',-1)
        
        npc_unit.career=srcdict.get('career',-1)
        
        npc_unit.gender=srcdict.get('gender',-1)
        
        npc_unit.npcId=srcdict.get('npcId',-1)
        
        npc_unit.idx=srcdict.get('idx',-1)
        
        npc_unit.pos=srcdict.get('pos',-1)
        
        npc_unit.hp=srcdict.get('hp',-1)
        
        npc_unit.attackId=srcdict.get('attackId',-1)
        
        npc_unit.physicalatk=srcdict.get('physicalatk',-1)
        
        npc_unit.physicaldef=srcdict.get('physicaldef',-1)
        
        npc_unit.magicatk=srcdict.get('magicatk',-1)
        
        npc_unit.magicdef=srcdict.get('magicdef',-1)
        
        npc_unit.furyAttackRate=srcdict.get('furyAttackRate',-1)
        
        npc_unit.hardAttackRate=srcdict.get('hardAttackRate',-1)
        
        npc_unit.hurtIncValue=srcdict.get('hurtIncValue',-1)
        
        npc_unit.hurtDecValue=srcdict.get('hurtDecValue',-1)
        
        npc_unit.hurtIncPercent=srcdict.get('hurtIncPercent',-1)
        
        npc_unit.hurtDecPercent=srcdict.get('hurtDecPercent',-1)
        
        npc_unit.skills=str(srcdict.get('skills',"")).replace("u'","'") 
        
        npc_unit.equipment=str(srcdict.get('equipment',"")).replace("u'","'") 
        
        npc_unit.style=str(srcdict.get('style',"")).replace("u'","'") 
        
        npc_unit.npcunitres = resources.getResource(cursor,npc_unit.deployId)
        
        npc_unitlist.append(npc_unit)
    return npc_unitlist

def clear_npc_unit():
    for npc_unit in Npc_unit.objects.all():
        npc_unit.delete()

def save_npc_unit(cursor,npc_unit):
    namelang = langs.setlang(ModelTypes.Type_Npc_unit,npc_unit.deployId, 'name', npc_unit.name)
    npc_unit.name = namelang.id
    desclang = langs.setlang(ModelTypes.Type_Npc_unit,npc_unit.deployId, 'desc', npc_unit.desc)
    npc_unit.desc = desclang.id
        
    npc_unit.save()



def extractShop_itemAction(request):
    try:
        cursor = connection.cursor()
        extract_shop_item(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_shop_item(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Shop_item,))
    srcdata = cursor.fetchall()
    shop_itemlist = trans_shop_item(cursor,srcdata)
    clear_shop_item()
    for shop_item in shop_itemlist :
        save_shop_item(cursor,shop_item)

def trans_shop_item(cursor,srcdata):
    shop_itemlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'shop_item',rawdata
        srcdict =  json.loads(rawdata)
        shop_item = Shop_item()
        shop_item.deployId = srcdict.get('id', 0)
        shop_item.tabId=srcdict.get('tabId',-1)
        
        shop_item.itemId=srcdict.get('itemId',-1)
        
        shop_item.coinPrice=srcdict.get('coinPrice',-1)
        
        shop_item.silverPrice=srcdict.get('silverPrice',-1)
        
        shop_item.status=srcdict.get('status',-1)
        
        shop_item.isDiscount=srcdict.get('isDiscount',-1)
        
        shop_item.coinPirceDiscount=srcdict.get('coinPirceDiscount',-1)
        
        shop_item.silverPriceDiscount=srcdict.get('silverPriceDiscount',-1)
        
        shop_item.levelLimit=srcdict.get('levelLimit',-1)
        
        shop_item.vipLevelLimit=srcdict.get('vipLevelLimit',-1)
        
        shop_item.rank=srcdict.get('rank',-1)
        
        shop_item.shop_itemres = resources.getResource(cursor,shop_item.deployId)
        
        shop_itemlist.append(shop_item)
    return shop_itemlist

def clear_shop_item():
    for shop_item in Shop_item.objects.all():
        shop_item.delete()

def save_shop_item(cursor,shop_item):
        
    shop_item.save()



def extractTavernAction(request):
    try:
        cursor = connection.cursor()
        extract_tavern(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_tavern(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Tavern,))
    srcdata = cursor.fetchall()
    tavernlist = trans_tavern(cursor,srcdata)
    clear_tavern()
    for tavern in tavernlist :
        save_tavern(cursor,tavern)

def trans_tavern(cursor,srcdata):
    tavernlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'tavern',rawdata
        srcdict =  json.loads(rawdata)
        tavern = Tavern()
        tavern.deployId = srcdict.get('id', 0)
        tavern.level=srcdict.get('level',-1)
        
        tavern.requiredLevel=srcdict.get('requiredLevel',-1)
        
        tavern.moneyType=srcdict.get('moneyType',-1)
        
        tavern.money=srcdict.get('money',-1)
        
        tavern.npcRates=str(srcdict.get('npcRates',[])).replace("u'","'")
        
        tavern.taskRates=str(srcdict.get('taskRates',[])).replace("u'","'")
        
        tavernlist.append(tavern)
    return tavernlist

def clear_tavern():
    for tavern in Tavern.objects.all():
        tavern.delete()

def save_tavern(cursor,tavern):
        
    tavern.save()



def extractVersus_battle_pointAction(request):
    try:
        cursor = connection.cursor()
        extract_versus_battle_point(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_versus_battle_point(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Versus_battle_point,))
    srcdata = cursor.fetchall()
    versus_battle_pointlist = trans_versus_battle_point(cursor,srcdata)
    clear_versus_battle_point()
    for versus_battle_point in versus_battle_pointlist :
        save_versus_battle_point(cursor,versus_battle_point)

def trans_versus_battle_point(cursor,srcdata):
    versus_battle_pointlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'versus_battle_point',rawdata
        srcdict =  json.loads(rawdata)
        versus_battle_point = Versus_battle_point()
        versus_battle_point.deployId = srcdict.get('id', 0)
        versus_battle_point.level=srcdict.get('level',-1)
        
        versus_battle_point.battlePointId=srcdict.get('battlePointId',-1)
        
        versus_battle_pointlist.append(versus_battle_point)
    return versus_battle_pointlist

def clear_versus_battle_point():
    for versus_battle_point in Versus_battle_point.objects.all():
        versus_battle_point.delete()

def save_versus_battle_point(cursor,versus_battle_point):
        
    versus_battle_point.save()



def extractConstantsAction(request):
    try:
        cursor = connection.cursor()
        extract_constants(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_constants(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Constants,))
    srcdata = cursor.fetchall()
    constantslist = trans_constants(cursor,srcdata)
    clear_constants()
    for constants in constantslist :
        save_constants(cursor,constants)

def trans_constants(cursor,srcdata):
    constantslist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'constants',rawdata
        srcdict =  json.loads(rawdata)
        constants = Constants()
        constants.deployId = srcdict.get('id', 0)
        constants.energeBoostPeriod=srcdict.get('energeBoostPeriod',-1)
        
        constants.energeBoostUnit=srcdict.get('energeBoostUnit',-1)
        
        constants.practiceDuration1=srcdict.get('practiceDuration1',-1)
        
        constants.practiceDuration2=srcdict.get('practiceDuration2',-1)
        
        constants.practiceDuration3=srcdict.get('practiceDuration3',-1)
        
        constants.practiceSpeedExtraExp=srcdict.get('practiceSpeedExtraExp',-1)
        
        constants.practiceCostCoeff1=srcdict.get('practiceCostCoeff1',-1)
        
        constants.practiceCostCoeff2=srcdict.get('practiceCostCoeff2',-1)
        
        constants.practiceCostCoeff3=srcdict.get('practiceCostCoeff3',-1)
        
        constants.practiceSpeedCost=srcdict.get('practiceSpeedCost',-1)
        
        constants.practiceDirectlyFinishCost=srcdict.get('practiceDirectlyFinishCost',-1)
        
        constants.practiceExpUnitCoeff1=srcdict.get('practiceExpUnitCoeff1',-1)
        
        constants.practiceExpUnitCoeff2=srcdict.get('practiceExpUnitCoeff2',-1)
        
        constants.practiceExpUnitCoeff3=srcdict.get('practiceExpUnitCoeff3',-1)
        
        constants.practiceSpeedItemId=srcdict.get('practiceSpeedItemId',-1)
        
        constants.versusItemId=srcdict.get('versusItemId',-1)
        
        constants.versusLevelLimit=srcdict.get('versusLevelLimit',-1)
        
        constantslist.append(constants)
    return constantslist

def clear_constants():
    for constants in Constants.objects.all():
        constants.delete()

def save_constants(cursor,constants):
        
    constants.save()



def extractForge_item_dataAction(request):
    try:
        cursor = connection.cursor()
        extract_forge_item_data(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_forge_item_data(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Forge_item_data,))
    srcdata = cursor.fetchall()
    forge_item_datalist = trans_forge_item_data(cursor,srcdata)
    clear_forge_item_data()
    for forge_item_data in forge_item_datalist :
        save_forge_item_data(cursor,forge_item_data)

def trans_forge_item_data(cursor,srcdata):
    forge_item_datalist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'forge_item_data',rawdata
        srcdict =  json.loads(rawdata)
        forge_item_data = Forge_item_data()
        forge_item_data.deployId = srcdict.get('id', 0)
        forge_item_data.count=srcdict.get('count',-1)
        
        forge_item_data.min=srcdict.get('min',-1)
        
        forge_item_data.max=srcdict.get('max',-1)
        
        forge_item_data.gold=srcdict.get('gold',-1)
        
        forge_item_datalist.append(forge_item_data)
    return forge_item_datalist

def clear_forge_item_data():
    for forge_item_data in Forge_item_data.objects.all():
        forge_item_data.delete()

def save_forge_item_data(cursor,forge_item_data):
        
    forge_item_data.save()



def extractItem_fragmentAction(request):
    try:
        cursor = connection.cursor()
        extract_item_fragment(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_item_fragment(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Item_fragment,))
    srcdata = cursor.fetchall()
    item_fragmentlist = trans_item_fragment(cursor,srcdata)
    clear_item_fragment()
    for item_fragment in item_fragmentlist :
        save_item_fragment(cursor,item_fragment)

def trans_item_fragment(cursor,srcdata):
    item_fragmentlist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'item_fragment',rawdata
        srcdict =  json.loads(rawdata)
        item_fragment = Item_fragment()
        item_fragment.deployId = srcdict.get('id', 0)
        item_fragment.itemId=srcdict.get('itemId',-1)
        
        item_fragment.type=srcdict.get('type',-1)
        
        item_fragment.fragments=str(srcdict.get('fragments',[])).replace("u'","'")
        
        item_fragmentlist.append(item_fragment)
    return item_fragmentlist

def clear_item_fragment():
    for item_fragment in Item_fragment.objects.all():
        item_fragment.delete()

def save_item_fragment(cursor,item_fragment):
        
    item_fragment.save()



def extractItem_extra_propAction(request):
    try:
        cursor = connection.cursor()
        extract_item_extra_prop(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_item_extra_prop(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Item_extra_prop,))
    srcdata = cursor.fetchall()
    item_extra_proplist = trans_item_extra_prop(cursor,srcdata)
    clear_item_extra_prop()
    for item_extra_prop in item_extra_proplist :
        save_item_extra_prop(cursor,item_extra_prop)

def trans_item_extra_prop(cursor,srcdata):
    item_extra_proplist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'item_extra_prop',rawdata
        srcdict =  json.loads(rawdata)
        item_extra_prop = Item_extra_prop()
        item_extra_prop.deployId = srcdict.get('id', 0)
        item_extra_prop.level=srcdict.get('level',-1)
        
        item_extra_prop.property=srcdict.get('property',-1)
        
        item_extra_prop.valueType=srcdict.get('valueType',-1)
        
        item_extra_prop.min=srcdict.get('min',-1)
        
        item_extra_prop.max=srcdict.get('max',-1)
        
        item_extra_proplist.append(item_extra_prop)
    return item_extra_proplist

def clear_item_extra_prop():
    for item_extra_prop in Item_extra_prop.objects.all():
        item_extra_prop.delete()

def save_item_extra_prop(cursor,item_extra_prop):
        
    item_extra_prop.save()



def extractItem_perfect_prop_dataAction(request):
    try:
        cursor = connection.cursor()
        extract_item_perfect_prop_data(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_item_perfect_prop_data(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Item_perfect_prop_data,))
    srcdata = cursor.fetchall()
    item_perfect_prop_datalist = trans_item_perfect_prop_data(cursor,srcdata)
    clear_item_perfect_prop_data()
    for item_perfect_prop_data in item_perfect_prop_datalist :
        save_item_perfect_prop_data(cursor,item_perfect_prop_data)

def trans_item_perfect_prop_data(cursor,srcdata):
    item_perfect_prop_datalist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'item_perfect_prop_data',rawdata
        srcdict =  json.loads(rawdata)
        item_perfect_prop_data = Item_perfect_prop_data()
        item_perfect_prop_data.deployId = srcdict.get('id', 0)
        item_perfect_prop_data.itemQuality=srcdict.get('itemQuality',-1)
        
        item_perfect_prop_data.type=srcdict.get('type',-1)
        
        item_perfect_prop_data.prop=srcdict.get('prop',-1)
        
        item_perfect_prop_data.min=srcdict.get('min',-1)
        
        item_perfect_prop_data.max=srcdict.get('max',-1)
        
        item_perfect_prop_datalist.append(item_perfect_prop_data)
    return item_perfect_prop_datalist

def clear_item_perfect_prop_data():
    for item_perfect_prop_data in Item_perfect_prop_data.objects.all():
        item_perfect_prop_data.delete()

def save_item_perfect_prop_data(cursor,item_perfect_prop_data):
        
    item_perfect_prop_data.save()



def extractHomeAction(request):
    try:
        cursor = connection.cursor()
        extract_home(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_home(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Home,))
    srcdata = cursor.fetchall()
    homelist = trans_home(cursor,srcdata)
    clear_home()
    for home in homelist :
        save_home(cursor,home)

def trans_home(cursor,srcdata):
    homelist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'home',rawdata
        srcdict =  json.loads(rawdata)
        home = Home()
        home.deployId = srcdict.get('id', 0)
        home.homeId=srcdict.get('homeId',-1)
        
        home.cellId=srcdict.get('cellId',-1)
        
        home.level=srcdict.get('level',-1)
        
        home.cardId=str(srcdict.get('cardId',[])).replace("u'","'")
        
        home.taskId=str(srcdict.get('taskId',[])).replace("u'","'")
        
        home.homeres = resources.getResource(cursor,home.deployId)
        
        homelist.append(home)
    return homelist

def clear_home():
    for home in Home.objects.all():
        home.delete()

def save_home(cursor,home):
        
    home.save()



def extractOpen_bagAction(request):
    try:
        cursor = connection.cursor()
        extract_open_bag(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_open_bag(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Open_bag,))
    srcdata = cursor.fetchall()
    open_baglist = trans_open_bag(cursor,srcdata)
    clear_open_bag()
    for open_bag in open_baglist :
        save_open_bag(cursor,open_bag)

def trans_open_bag(cursor,srcdata):
    open_baglist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'open_bag',rawdata
        srcdict =  json.loads(rawdata)
        open_bag = Open_bag()
        open_bag.deployId = srcdict.get('id', 0)
        open_bag.bagCount=srcdict.get('bagCount',-1)
        
        open_bag.gold=srcdict.get('gold',-1)
        
        open_baglist.append(open_bag)
    return open_baglist

def clear_open_bag():
    for open_bag in Open_bag.objects.all():
        open_bag.delete()

def save_open_bag(cursor,open_bag):
        
    open_bag.save()



def extractSilver_bagAction(request):
    try:
        cursor = connection.cursor()
        extract_silver_bag(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_silver_bag(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Silver_bag,))
    srcdata = cursor.fetchall()
    silver_baglist = trans_silver_bag(cursor,srcdata)
    clear_silver_bag()
    for silver_bag in silver_baglist :
        save_silver_bag(cursor,silver_bag)

def trans_silver_bag(cursor,srcdata):
    silver_baglist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'silver_bag',rawdata
        srcdict =  json.loads(rawdata)
        silver_bag = Silver_bag()
        silver_bag.deployId = srcdict.get('id', 0)
        silver_bag.itemId=srcdict.get('itemId',-1)
        
        silver_bag.silvers=str(srcdict.get('silvers',[])).replace("u'","'")
        
        silver_baglist.append(silver_bag)
    return silver_baglist

def clear_silver_bag():
    for silver_bag in Silver_bag.objects.all():
        silver_bag.delete()

def save_silver_bag(cursor,silver_bag):
        
    silver_bag.save()



def extractGift_bagAction(request):
    try:
        cursor = connection.cursor()
        extract_gift_bag(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_gift_bag(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Gift_bag,))
    srcdata = cursor.fetchall()
    gift_baglist = trans_gift_bag(cursor,srcdata)
    clear_gift_bag()
    for gift_bag in gift_baglist :
        save_gift_bag(cursor,gift_bag)

def trans_gift_bag(cursor,srcdata):
    gift_baglist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'gift_bag',rawdata
        srcdict =  json.loads(rawdata)
        gift_bag = Gift_bag()
        gift_bag.deployId = srcdict.get('id', 0)
        gift_bag.itemId=srcdict.get('itemId',-1)
        
        gift_bag.reward=str(srcdict.get('reward',{})).replace("u'","'")
        
        gift_baglist.append(gift_bag)
    return gift_baglist

def clear_gift_bag():
    for gift_bag in Gift_bag.objects.all():
        gift_bag.delete()

def save_gift_bag(cursor,gift_bag):
        
    gift_bag.save()



def extractTreasureAction(request):
    try:
        cursor = connection.cursor()
        extract_treasure(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def extract_treasure(cursor):
    pullsql = """ select id,deploy_id,name,dict from dic_game where `type`=%s """
    cursor.execute(pullsql,(ModelTypes.Type_Treasure,))
    srcdata = cursor.fetchall()
    treasurelist = trans_treasure(cursor,srcdata)
    clear_treasure()
    for treasure in treasurelist :
        save_treasure(cursor,treasure)

def trans_treasure(cursor,srcdata):
    treasurelist = []
    for data in srcdata :
        rawdata = data[3].replace("'","\"")
        print 'treasure',rawdata
        srcdict =  json.loads(rawdata)
        treasure = Treasure()
        treasure.deployId = srcdict.get('id', 0)
        treasure.itemId=srcdict.get('itemId',-1)
        
        treasure.items=str(srcdict.get('items',[])).replace("u'","'")
        
        treasurelist.append(treasure)
    return treasurelist

def clear_treasure():
    for treasure in Treasure.objects.all():
        treasure.delete()

def save_treasure(cursor,treasure):
        
    treasure.save()


def getLanguage(cursor,deployId,key):
    sql = """ select value from dic_language where `deploy_id` = %s and `key` = %s """
    cursor.execute(sql,(deployId,key))
    result = cursor.fetchone()
    if not result:
        return "";
    return result[0]